package com.xiang.community.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.xiang.community.annotation.LoginRequired;
import com.xiang.community.bo.MessageBO;
import com.xiang.community.dto.PageResult;
import com.xiang.community.dto.ResultDTO;
import com.xiang.community.entity.Comment;
import com.xiang.community.entity.DiscussPost;
import com.xiang.community.entity.User;
import com.xiang.community.enums.CommentStatusEnum;
import com.xiang.community.enums.CommentTypeEnum;
import com.xiang.community.enums.ResponseCodeEnum;
import com.xiang.community.message.MessageProducer;
import com.xiang.community.service.CommentService;
import com.xiang.community.service.CommonService;
import com.xiang.community.service.DiscussPostService;
import com.xiang.community.service.UserService;
import com.xiang.community.utils.CookieUtil;
import com.xiang.community.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.xiang.community.constant.KafkaConstant.TOPIC_COMMENT;
import static com.xiang.community.constant.LoginConstant.MAP_KEY_TOKEN;
import static com.xiang.community.constant.RedisUtilConstant.PREFIX_USER_ID;

@RestController
@RequestMapping("/comment")
@Slf4j
public class CommentController {

    @Resource
    private CommentService commentService;
    @Resource
    private UserService userService;
    @Resource
    private DiscussPostService discussPostService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private HttpServletRequest request;
    @Resource
    private CommonService commonService;
    @Resource
    private MessageProducer messageProducer;
    @Resource
    private ObjectMapper mapper;

    /**
     * 分页获取帖子评论
     *
     * @param postId
     * @param index
     * @param size
     * @return
     */
    @GetMapping("/{postId}/{index}/{size}")
    public PageResult getCommentList(@PathVariable Integer postId, @PathVariable Integer index, @PathVariable Integer size) {
        PageInfo<Comment> pageInfo = commentService.findCommentsByEntity(CommentTypeEnum.COMMENT.getType(), postId, index, size);
        List<Map<String, Object>> list = new ArrayList<>(pageInfo.getList().size());
        for (Comment comment : pageInfo.getList()) {
            Map<String, Object> map = new HashMap<>(2);
            map.put("comment", comment);
            User poster = userService.findUserById(comment.getUserId());
            map.put("poster", poster);
            list.add(map);
        }
        return PageResult.getInstance(pageInfo.getTotal(), list);
    }

    /**
     * 发布评论
     *
     * @param postId
     * @param data
     * @return
     */
    @LoginRequired
    @PostMapping("/{postId}")
    public ResultDTO saveComment(@PathVariable Integer postId, @RequestBody Map<String, String> data) {
        String content = HtmlUtils.htmlEscape(data.get("content"));
        if (StringUtils.isBlank(content)) {
            return ResultDTO.builder()
                    .code(ResponseCodeEnum.CLIENT_ERROR.getCode())
                    .message("帖子参数错误")
                    .build();
        }

        String currentUserId = redisUtil.getValueFromString(PREFIX_USER_ID, CookieUtil.getValue(request, MAP_KEY_TOKEN));
        User user = commonService.getUserByUserId(currentUserId);
        Comment comment = Comment.builder()
                .content(content)
                .createTime(new Date())
                .entityId(postId)
                .entityType(CommentTypeEnum.COMMENT.getType())
                .status(CommentStatusEnum.ALIVE.getStatus())
                .targetId(0)
                .userId(user.getId())
                .build();
        commentService.addComment(comment);

        // 更新评论数
        DiscussPost discussPost = discussPostService.findOne(postId);
        discussPostService.updateValue(postId, "comment_count", discussPost.getCommentCount() + 1);

        // 评论消息
        Map<String, Object> map = new HashMap<>(2);
        map.put("discussPostTitle", discussPost.getTitle());
        map.put("commentContent", content);
        MessageBO messageBO = MessageBO.builder()
                .fromUserName(user.getUsername()).toUserId(discussPost.getUserId())
                .data(map).build();
        try {
            messageProducer.sendMessage(TOPIC_COMMENT, mapper.writeValueAsString(messageBO));
        } catch (JsonProcessingException e) {
            log.error(e.toString());
        }

        return ResultDTO.builder().code(ResponseCodeEnum.SUCCESS.getCode()).build();
    }
}
